package com.ckmod.zyr3x.tools.components;

import android.util.Log;

import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;

public class CSystem {

    private static final String TAG = "CKZTools.CSystem";
    public static void mountSystem()
    {
       rootCommand("mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system");
    }

    public static void chmod(String mode,String dir)
    {
       rootCommand("chmod "+mode+" "+dir);
    }

    public static void unmountSystem()
    {
        rootCommand("mount -o remount,ro /system");
    }

    public static void rootCommand(String cmd)
    {
        File wd = new File("/");
        System.out.println(wd);
        Process proc = null;
        try {
            proc = Runtime.getRuntime().exec("su", null, wd);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (proc != null) {
            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
            out.println(cmd);
            out.println("exit");
            try {
                proc.waitFor();
                out.close();
                proc.destroy();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void kill(String name)
    {
         String kill = "kill -9 `pidof " + name + "`";
         rootCommand(kill);
    }

    public static String rootCommandOut(String cmd)
    {
        String line = null;
        File wd = new File("/");

        Process proc = null;
        try {
            proc = Runtime.getRuntime().exec("su", null, wd);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (proc != null) {
            BufferedReader in = new BufferedReader(new InputStreamReader(proc.getInputStream()));
            PrintWriter out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(proc.getOutputStream())), true);
            out.println(cmd);
            out.println("exit");
            try {

                while ((line = in.readLine()) != null) {}
                proc.waitFor();
                in.close();
                out.close();
                proc.destroy();

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return line;
    }

    public static String readOneLine(String fname) {
        BufferedReader br;
        String line = null;

        try {
            br = new BufferedReader(new FileReader(fname), 512);
            try {
                line = br.readLine();
            } finally {
                br.close();
            }
        } catch (Exception e) {
            Log.e(TAG, "IO Exception when reading /sys/ file", e);
        }
        return line;
    }
}
